import { app, BrowserWindow, clipboard } from 'electron'
import path from 'path'

export class ClipboardHistoryService {
  private history: string[] = []
  private maxHistory = 100
  private win: BrowserWindow | null = null

  constructor() {
    // 监听系统剪贴板变化（可选：定时轮询或主进程拦截）
    setInterval(() => {
      const text = clipboard.readText()
      if (text && text !== this.history[0]) {
        this.addHistory(text)
      }
    }, 1000)
  }

  addHistory(text: string) {
    if (!text) return
    if (this.history[0] === text) return
    this.history.unshift(text)
    if (this.history.length > this.maxHistory) {
      this.history = this.history.slice(0, this.maxHistory)
    }
    // 新增：通知所有窗口刷新
    BrowserWindow.getAllWindows().forEach((win) => {
      win.webContents.send('clipboard-history-updated')
    })
  }

  getHistory() {
    return this.history
  }

  clearHistory() {
    this.history = []
  }

  openWindow() {
    if (this.win && !this.win.isDestroyed()) {
      this.win.focus()
      return
    }
    this.win = new BrowserWindow({
      width: 420,
      height: 520,
      resizable: true,
      alwaysOnTop: true,
      skipTaskbar: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false, // 保证 window.api 可用
        preload: path.join(__dirname, '../preload/index.js')
      }
    })
    // 路径修正，兼容开发和打包
    const htmlPath = path.join(app.getAppPath(), 'src/main/clipboard-history.html')
    this.win.loadFile(htmlPath)
    this.win.on('closed', () => {
      this.win = null
    })
  }

  closeWindow() {
    if (this.win && !this.win.isDestroyed()) {
      this.win.close()
      this.win = null
    }
  }
}

export const clipboardHistoryService = new ClipboardHistoryService()
